const { exec, execSync } = window.require('child_process');
const fs = window.require('fs');
import { block_sleep } from './utils.js';
import { collect_data_list } from '../data_collect.tsx';
const { ipcRenderer } = window.require("electron");

function generate_cmd_prefix(tool_path, dev_id) {
    if (tool_path.length === 0 || dev_id.length === 0)
        return '';

    return `${tool_path} -t ${dev_id}`;;
}

function wait_for_app_list_finish(cmd_prefix, dev_tool_file_path) {
    let cmd = `${cmd_prefix} shell "ls -al ${dev_tool_file_path}/appnamesend.txt"`;
    let wait_time = 0;
    let check_interval = 100;
    let wait_timeout = 8000;

    while (wait_time < wait_timeout) {
        try {
            let ret = execSync(cmd).toString();
            if (ret.indexOf('No such file or directory') < 0)
                break;
        } catch (err) {}
        block_sleep(check_interval);
        wait_time += check_interval;
    }

    if (wait_time >= wait_timeout) {
        return -1;
    }
    return 0;
}

export function openharmony_get_app_list(tool_path, dev_id) {
    let cmd_prefix = generate_cmd_prefix(tool_path, dev_id);
    let dev_tool_file_path = '/data/app/el2/100/base/com.ohos.editorapp/haps/entry/files';
    let cmd = `${cmd_prefix} shell "rm -rf ${dev_tool_file_path}/appnamesend.txt"`;
    try {
        execSync(cmd);
    } catch (err) {}

    ipcRenderer.invoke("getAllAppListByHdc", dev_id);

    if (wait_for_app_list_finish(cmd_prefix, dev_tool_file_path) < 0)
        return [];

    let cur_dist = tool_path.substring(0, 3);
    cmd = `${cmd_prefix} file recv ${dev_tool_file_path}/appnames.txt ${cur_dist}`;
    try {
        execSync(cmd);
    } catch (err) {
        return [];
    }

    let app_list_data = fs.readFileSync(cur_dist + 'appnames.txt', { encoding: "utf-8" });
    var app_list_json = JSON.parse(app_list_data);
    let return_list = [];
    for (let app of app_list_json.allAppList) {
        let item = { name: app.name, icon: app.icon, package: app.package };
        return_list.push(item);
    }

    try {
        fs.unlinkSync(cur_dist + 'appnames.txt');
    } catch (err) {}
    return return_list;
}

export function openharmony_start_app(package_name, tool_path, dev_id) {
    let cmd_prefix = generate_cmd_prefix(tool_path, dev_id);
    let cmd = cmd_prefix + ' shell \"wukong appinfo\"';
    let app_info = '';
    try {
        app_info = execSync(cmd).toString();
    } catch (err) {
        return -1;
    }

    let lines = app_info.split(/[(\r\n)\r\n]/);
    let bundle;
    let ability;
    for (let line of lines) {
        let paras = line.split(' ');
        if (line.startsWith('BundleName:')) {
            bundle = paras[2];
        }

        if (line.startsWith('AbilityName:')) {
            if (bundle === package_name) {
                ability = paras[2];
                break;
            }
        }
    }

    cmd = `${cmd_prefix} shell "aa start -a ${ability} -b ${bundle}"`;
    try {
        execSync(cmd)
    } catch (err) {
        console.log(err);
        return -1;
    }

    return 0;
}

export function openharmony_start_collect(package_name, tool_path, dev_id, data_mask) {
    let cmd_prefix = generate_cmd_prefix(tool_path, dev_id);
    let cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/sp_stop"`;
    try {
        execSync(cmd);
    } catch (err) {
        return -1;
    }

    cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/t_general_info.csv"`;
    try {
        execSync(cmd);
    } catch (err) {
        return -1;
    }

    cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/t_index_info.csv"`;
    try {
        execSync(cmd);
    } catch (err) {
        return -1;
    }

    cmd = `${cmd_prefix} shell "/data/local/tmp/SP_daemon -INTERVAL 1000 -PKG ${package_name}  -c -g -t -p -f"`;

    try {
        exec(cmd);
    } catch (err) {
        return -1;
    }

    return 0;
}

export function openharmony_stop_collect(tool_path, dev_id, report_path) {
    let cmd_prefix = generate_cmd_prefix(tool_path, dev_id);
    let cmd = `${cmd_prefix} shell "touch /data/local/tmp/sp_stop"`;
    try {
        execSync(cmd);
    } catch (err) {
        return -1;
    }

    let wait_time = 0;
    let check_interval = 100;
    let wait_timeout = 2000;

    cmd = `${cmd_prefix} shell "ls -al /data/local/tmp/t_general_info.csv"`;
    while (wait_time < wait_timeout) {
        try {
            let ret = execSync(cmd).toString();
            if (ret.indexOf('No such file or directory') < 0)
                break;
        } catch (err) {}
        block_sleep(check_interval);
        wait_time += check_interval;
    }

    if (wait_time >= wait_timeout)
        return -1;
    block_sleep(check_interval);

    let cur_dist = report_path.substring(0, 3);
    if (report_path.length > 0) {
        cmd = `${cmd_prefix} file recv /data/local/tmp/t_general_info.csv ${cur_dist}`;
        try {
            execSync(cmd);
        } catch (err) {}

        cmd = `${cmd_prefix} file recv /data/local/tmp/t_index_info.csv ${cur_dist}`;
        try {
            execSync(cmd);
        } catch (err) {}
    }

    try {
        fs.accessSync(cur_dist + 't_general_info.csv', fs.constants.R_OK);
        try {
            fs.rename(cur_dist + 't_general_info.csv', report_path + '\\' + 't_general_info.csv', ()=>{});
        } catch (err) {}

        fs.accessSync(cur_dist + 't_index_info.csv', fs.constants.R_OK);
        try {
            fs.rename(cur_dist + 't_index_info.csv', report_path + '\\' + 't_index_info.csv', ()=>{});
        } catch (err) {}
    } catch (err) {}

    cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/t_general_info.csv"`;
    try {
        execSync(cmd);
    } catch (err) {}

    cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/t_index_info.csv"`;
    try {
        execSync(cmd);
    } catch (err) {}

    cmd = `${cmd_prefix} shell "rm -rf /data/local/tmp/sp_stop"`;
    try {
        execSync(cmd);
    } catch (err) {}

    return 0;
}